#include "stdafx.h"
#include "image.h"
#pragma comment(lib,"msimg32.lib")

CImage::CImage(HINSTANCE hInst,TCHAR * fileName){
	hbmp=(HBITMAP)LoadImage(hInst,fileName,IMAGE_BITMAP,0,0,LR_LOADFROMFILE);
	HDC wndDC=GetDC(NULL);
	memDC=CreateCompatibleDC(wndDC);
	SelectObject(memDC,hbmp);
	ReleaseDC(NULL,wndDC);
    BITMAP bmpinfo;
	ZeroMemory(&bmpinfo,sizeof(BITMAP));
	GetObject(hbmp,sizeof(BITMAP),&bmpinfo);
	this->width=bmpinfo.bmWidth;
	this->height=bmpinfo.bmHeight;

}

CImage::~CImage(){
	DeleteObject(hbmp);
	DeleteDC(memDC);
}

void CImage::Draw(HDC hdc, int x, int y, int w, int h, int srcX, int srcY){
	BitBlt(hdc,x,y,w,h,memDC,srcX,srcY,SRCCOPY);

}

void CImage::Draw(HDC hdc, int x,int y){
BitBlt(hdc,x,y,width,height,memDC,0,0,SRCCOPY);
}

void CImage::TransDraw(HDC hdc, int x, int y, int w, int h, int srcX, int srcY){
	HDC maskDC=CreateCompatibleDC(hdc);
	HBITMAP maskBMP=CreateBitmap(width,height,1,1,NULL);
	SelectObject(maskDC,maskBMP);
	COLORREF maskColor=GetPixel(memDC,0,0);
	SetBkColor(memDC,maskColor);
	BitBlt(maskDC,0,0,width,height,memDC,0,0,SRCCOPY);
	BitBlt(hdc,x,y,w,h,memDC,srcX,srcY,SRCINVERT);
	BitBlt(hdc,x,y,w,h,maskDC,srcX,srcY,SRCAND);
	BitBlt(hdc,x,y,w,h,memDC,srcX,srcY,SRCINVERT);
	DeleteDC(maskDC);
	DeleteObject(maskBMP);
}
void CImage::TransDraw(HDC hdc, int x, int y){
	this->TransDraw(hdc,x,y,width,height,0,0);
}

void CImage::AlphaDraw(HDC hdc, int x, int y, int w, int h, int srcX,int srcY,int alpha){
	BLENDFUNCTION alphaFun;
	alphaFun.AlphaFormat=0;
	alphaFun.BlendFlags=0;
	alphaFun.BlendOp=AC_SRC_OVER;
	alphaFun.SourceConstantAlpha=alpha;
	AlphaBlend(hdc,x,y,w,h,memDC,srcX,srcY,w,h,alphaFun);
}

void CImage::AlphaDraw(HDC hdc, int x, int y,int alpha){
	this->AlphaDraw(hdc,x,y,width,height,0,0,alpha);
}

void DrawString(HDC hdc,TCHAR * str,int x,int y, int height,TCHAR * fontName,COLORREF color){
	HFONT hFont=CreateFont(height,0,0,0,0,0,0,0,GB2312_CHARSET,0,0,0,0,fontName);
	COLORREF oldcolor=GetTextColor(hdc);
	int bkmode=GetBkMode(hdc);
	HFONT oldFont=(HFONT)SelectObject(hdc,hFont);
	SetBkMode(hdc,TRANSPARENT);
	SetTextColor(hdc,color);
	TextOut(hdc,x,y,str,_tcslen(str));
	SetTextColor(hdc,oldcolor);
	SetBkMode(hdc,bkmode);
	SelectObject(hdc,oldFont);
	DeleteObject(hFont);
}

void DrawString(HDC hdc,TCHAR * str,RECT *rect,int height,TCHAR * fontName,COLORREF color){
	HFONT hFont=CreateFont(height,0,0,0,0,0,0,0,GB2312_CHARSET,0,0,0,0,fontName);
	COLORREF oldcolor=GetTextColor(hdc);
	int bkmode=GetBkMode(hdc);
	HFONT oldFont=(HFONT)SelectObject(hdc,hFont);
	SetBkMode(hdc,TRANSPARENT);
	SetTextColor(hdc,color);
	DrawText(hdc,str,_tcslen(str),rect,DT_VCENTER);
	//TextOut(hdc,x,y,str,_tcslen(str));
	SetTextColor(hdc,oldcolor);
	SetBkMode(hdc,bkmode);
	SelectObject(hdc,oldFont);
	DeleteObject(hFont);
}